package com.itheima.server.service.impl;

import com.itheima.server.mapper.BusinessMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.server.Enum.ClueStatus;
import com.itheima.server.domain.Business;
import com.itheima.server.domain.Clue;
import com.itheima.server.domain.Contract;
import com.itheima.server.dto.IndexInfoDto;
import com.itheima.server.mapper.ClueMapper;
import com.itheima.server.service.ClueService;
import com.itheima.server.service.ContractService;
import com.itheima.server.service.IBusinessService;
import com.itheima.server.service.IndexService;
import com.itheima.server.vo.BusinessChangeStatisticsVo;
import com.itheima.server.vo.DeptBusVo;
import org.springframework.beans.factory.annotation.Autowired;
import com.itheima.server.vo.IndexCluDragonTigerVo;
import com.itheima.server.vo.IndexInfoVo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.List;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

@Service
@AllArgsConstructor
public class IndexServiceControllerImpl implements IndexService {
    @Autowired
    private BusinessMapper businessMapper;

    /**
     * 获取商机转换统计
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    public List<BusinessChangeStatisticsVo> getBusinessChangeStatistics(LocalDate beginCreateTime, LocalDate endCreateTime) {
        //将LocalDate转换成LocalDateTime
        LocalDateTime begin = beginCreateTime.atStartOfDay();
        LocalDateTime end = endCreateTime.atTime(23, 59, 59);
        List<BusinessChangeStatisticsVo> list = businessMapper.getBusinessChangeStatistics(begin,end);
        //查询在时间段内的所有商机 在某个部门的总数
        List<DeptBusVo> map = businessMapper.getDeptBusinessCount(begin,end);

        if (ObjectUtils.isEmpty(map)) {
            return list;
        }

        for (BusinessChangeStatisticsVo bus : list) {
            for (DeptBusVo busVo : map) {
                if (!ObjectUtils.isEmpty(bus.getDeptName())){
                    if (bus.getDeptName().equals(busVo.getDeptName())) {
                        DecimalFormat df = new DecimalFormat("#.00");
                        String result = df.format(((double) bus.getNum() / busVo.getNum()) * 100);
                        bus.setRadio(Double.parseDouble(result));
                    }
                }
            }
        }

        Iterator<BusinessChangeStatisticsVo> iterator = list.iterator();
        while (iterator.hasNext()) {
            BusinessChangeStatisticsVo bus = iterator.next();
            if (ObjectUtils.isEmpty(bus.getDeptName())) {
                iterator.remove(); // 使用迭代器的 remove 方法安全删除
            }
        }


        return list;
    }

    private final ClueService clueService;
    private final IBusinessService businessService;
    private final ContractService contractService;
    private final ClueMapper clueMapper;

    /**
     * 首页基本信息
     * @param dto
     * @return
     */
    @Override
    public IndexInfoVo indexInfo(IndexInfoDto dto) {
        IndexInfoVo vo = new IndexInfoVo();
        try {
            indexClueInfo(vo,dto);
            indexBusInfo(vo,dto);
            indexConInfo(vo,dto);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return vo;
    }

    @Override
    public List<IndexCluDragonTigerVo> getCluDragonTiger(LocalDate begin, LocalDate end) {
      List<IndexCluDragonTigerVo> reslut =  clueMapper.getCluDragonTiger(begin,end);
        return reslut;
    }

    /**
     * 获取基本信息的线索信息
     * @param vo
     */
    private void indexClueInfo(IndexInfoVo vo,IndexInfoDto dto){
        String createTime = dto.getBeginCreateTime();
        String endTime = dto.getEndCreateTime();
        LambdaQueryWrapper<Clue> wrapper = new LambdaQueryWrapper<>();
        //排除伪线索
        wrapper.ne(Clue::getStatus, ClueStatus.INVALID.status);
        //时间区间
        wrapper.between(Clue::getCreateTime,createTime,endTime);
        //查询总线索数
        Integer count = clueService.count(wrapper);
        vo.setCluesNum(count==null?0:count);
        //查询今日线索数
        wrapper.clear();
        wrapper.ne(Clue::getStatus, ClueStatus.INVALID.status);
        LocalDate nowdate = LocalDate.now();
        LocalDateTime nowbegTime = nowdate.atStartOfDay();
        LocalDateTime nowendTime = nowdate.plusDays(1).atStartOfDay();
        wrapper.between(Clue::getCreateTime,nowbegTime,nowendTime);
        count = clueService .count(wrapper);
        vo.setTodayCluesNum(count==null?0:count);
        //待分配线索数
        wrapper.clear();
        wrapper.between(Clue::getCreateTime,createTime,endTime);
        wrapper.eq(Clue::getOwner,null);
        count = clueService.count(wrapper);
        vo.setToallocatedCluesNum(count==null?0:count);
        //待跟进线索数
        wrapper.clear();
        wrapper.between(Clue::getCreateTime,createTime,endTime);
        wrapper.eq(Clue::getStatus,ClueStatus.PENDING.status);
        count = clueService.count(wrapper);
        vo.setTofollowedCluesNum(count==null?0:count);
    }

    /**
     * 获取商机信息
     * @param vo
     * @param dto
     */
    private void indexBusInfo(IndexInfoVo vo,IndexInfoDto dto){
        String createTime = dto.getBeginCreateTime();
        String endTime = dto.getEndCreateTime();
        LambdaQueryWrapper<Business> wrapper = new LambdaQueryWrapper<>();
        //时间区间
        wrapper.between(Business::getCreateTime,createTime,endTime);
        //查询总商机数
        Integer count = businessService.count(wrapper);
        vo.setBusinessNum(count==null?0:count);
        //查询今日商机数
        wrapper.clear();
        LocalDate nowdate = LocalDate.now();
        LocalDateTime nowbegTime = nowdate.atStartOfDay();
        LocalDateTime nowendTime = nowdate.plusDays(1).atStartOfDay();
        wrapper.between(Business::getCreateTime,nowbegTime,nowendTime);
        count = businessService .count(wrapper);
        vo.setTodayBusinessNum(count==null?0:count);
        //待分配商机数
        wrapper.clear();
        wrapper.between(Business::getCreateTime,createTime,endTime);
        wrapper.eq(Business::getOwner,null);
        count = businessService.count(wrapper);
        vo.setToallocatedBusinessNum(count==null?0:count);
        //待跟进商机数
        wrapper.clear();
        wrapper.between(Business::getCreateTime,createTime,endTime);
        wrapper.eq(Business::getStatus,ClueStatus.PENDING.status);
        count = businessService.count(wrapper);
        vo.setTofollowedBusinessNum(count==null?0:count);
    }

    private void indexConInfo(IndexInfoVo vo,IndexInfoDto dto){
        String createTime = dto.getBeginCreateTime();
        String endTime = dto.getEndCreateTime();
        LambdaQueryWrapper<Contract> wrapper = new LambdaQueryWrapper<>();
        //时间区间
        wrapper.between(Contract::getCreateTime,createTime,endTime);
        //排除无效合同
        wrapper.eq(Contract::getStatus,1);
        //查询总合同数
        Integer count = contractService.count(wrapper);
        vo.setContractNum(count==null?0:count);
        //查询今日合同数
        wrapper.clear();
        wrapper.eq(Contract::getStatus,1);
        LocalDate nowdate = LocalDate.now();
        LocalDateTime nowbegTime = nowdate.atStartOfDay();
        LocalDateTime nowendTime = nowdate.plusDays(1).atStartOfDay();
        wrapper.between(Contract::getCreateTime,nowbegTime,nowendTime);
        count = contractService .count(wrapper);
        vo.setTodayContractNum(count==null?0:count);

        //查询总销售额
        LocalDateTime beg = LocalDate.parse(createTime, DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay();
        LocalDateTime end = LocalDate.parse(endTime, DateTimeFormatter.ofPattern("yyyy-MM-dd")).atTime(23, 59, 59);
        BigDecimal totalAmount = getContractAmount(beg, end);
        BigDecimal bigDecimal = new BigDecimal(0);
        vo.setSalesAmount(totalAmount==null?bigDecimal:totalAmount);

        //查询今日销售额
        BigDecimal todayAmount = getContractAmount(nowbegTime, nowendTime);
        vo.setTodaySalesAmount(todayAmount==null?bigDecimal:todayAmount);

    }

    /**
     * 获取时间区间内合同订单
     *
     * @param begTime
     * @param endTime
     * @return
     */
    public BigDecimal getContractAmount(LocalDateTime begTime, LocalDateTime endTime) {
        QueryWrapper<Contract> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("SUM(orders) as totalAmount");
        queryWrapper.between("create_time", begTime, endTime);
        queryWrapper.eq("status", 1);
        List<Map<String, Object>> result = contractService.listMaps(queryWrapper);
        BigDecimal totalAmount = BigDecimal.ZERO;
        if (!result.isEmpty() && result.get(0)!=null&&result.get(0).get("totalAmount") != null) {
            totalAmount = new BigDecimal(result.get(0).get("totalAmount").toString());
        }
        return totalAmount;
    }




}
